﻿using System;
using System.Diagnostics;
using Gwn.Library.MvpVm.Loggers;
using Microsoft.Practices.Prism.Logging;

namespace Gwn.Library.MvpVm.Extensions
{
    /// <summary>
    /// ILoggerFacade extension
    /// </summary>
    public static class LoggerFacadeExtension
    {

        private static string Wrapper(string message)
        {
            // Skip past this and the below frames
            var frame = new StackTrace().GetFrame(2);

            return string.Format(":{0}:{1}({2}) => {3} <= |{4}| ",
                frame.GetMethod().DeclaringType.Name,
                frame.GetMethod().Name, 
                frame.GetNativeOffset(),
                message.Replace("~","\r\n\t\t"),
                frame.GetMethod().DeclaringType.FullName
                );    
        }

        /// <summary>
        /// Logs the specified logger.
        /// </summary>
        /// <param name="logger">The logger.</param>
        /// <param name="formatString">The format string.</param>
        /// <param name="parameters">The parameters.</param>
        /// <returns></returns>
        public static ILoggerFacade Log(this ILoggerFacade logger, string formatString, params object[] parameters )
        {
#if DEBUG
            if (logger == null) logger = new DebugLogger();

            logger.Log(Wrapper(string.Format(formatString,parameters)), Category.Debug, Priority.None);
#endif
            return logger;
        }

        /// <summary>
        /// Logs the debug message
        /// </summary>
        /// <param name="logger">The logger.</param>
        /// <param name="message">The message.</param>
        /// <param name="type">The type.</param>
        /// <returns></returns>
        public static ILoggerFacade LogDebug(this ILoggerFacade logger, string message, Type type)
        {

#if DEBUG
            if (logger == null) logger = new DebugLogger();

            var newMsg = string.Format("{0} [{1}]", message, type.FullName);
            logger.Log(Wrapper(newMsg), Category.Debug, Priority.None);
#endif
            return logger;
        }

        /// <summary>
        /// Logs the exception.
        /// </summary>
        /// <param name="logger">The logger.</param>
        /// <param name="message">The message.</param>
        /// <param name="type">The type.</param>
        /// <returns></returns>
        public static ILoggerFacade LogException(this ILoggerFacade logger, string message, Type type)
        {
#if DEBUG
            if (logger == null) logger = new DebugLogger();

            var newMsg = string.Format("{0} [{1}]", message, type.FullName);
            logger.Log(Wrapper(newMsg), Category.Exception, Priority.High);
#endif
            return logger;
        }
    }
}
